package com.lagou.edu.service.impl;

import com.lagou.edu.dao.CodeDao;
import com.lagou.edu.feign.EmailFeign;
import com.lagou.edu.pojo.Auth;
import com.lagou.edu.service.CodeService;
import com.lagou.edu.util.CodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CodeServiceImpl implements CodeService {
    @Autowired
    private CodeDao codeDao;
    @Autowired
    private EmailFeign emailFeign;

    @Transactional(readOnly = true)
    @Override
    public List<Auth> findByEmailAndCode(String email, String code) {
        return codeDao.findByEmailAndCode(email, code);
    }

    @Override
    public Boolean createCode(String email) {
        // 生成验证码
        String code = CodeUtil.generaterRandCode(6);//6是生成6位数验证码

        // 发送邮件
        Boolean flag = emailFeign.sendEmail(email, code);

        // 保存验证码
        Auth auth = new Auth();
        auth.setEmail(email);
        auth.setCode(code);
        Date newDate = new Date();
        Date expire = new Date(newDate.getTime() + 60000);// 加一分钟
        auth.setCreatetime(newDate);
        auth.setExpiretime(expire);
        codeDao.save(auth);

        return flag;
    }

}
